<?php
App::uses('AppModel', 'Model');
/**
 * DisciplinesTeacher Model
 *
 * @property Teacher $Teacher
 * @property Discipline $Discipline
 */
class DisciplinesTeacher extends AppModel {

/**
 * Validation rules
 *
 * @var array
 */
	public $validate = array(
		'teacher_id' => array(
			'numeric' => array(
				'rule' => array('numeric'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'discipline_id' => array(
			'numeric' => array(
				'rule' => array('numeric'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
	);

	//The Associations below have been created with all possible keys, those that are not needed can be removed

/**
 * belongsTo associations
 *
 * @var array
 */
	public $belongsTo = array(
		'Teacher' => array(
			'className' => 'Teacher',
			'foreignKey' => 'teacher_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'Discipline' => array(
			'className' => 'Discipline',
			'foreignKey' => 'discipline_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		)
	);


	public $findMethods = array('available' =>  true);

    protected function _findAvailable($state, $query, $results = array()) {
        if ($state == 'before') {
        	//array('fields' => array('discipline_id', 'COUNT(*)'), 'group' => 'discipline_id'))
			$query['fields'] = array(
				'discipline_id',
				'COUNT(*)'
				);
			$query['group'] = 'discipline_id';
            return $query;
        }
        elseif($state == 'after'){
        	$results2 = array();
        	foreach ($results as $value) {
        		$results2[$value['DisciplinesTeacher']['discipline_id']] = $value[0]['count'];
        	}
        	$results = $results2;
        }
        return $results;
    }

    public function countWeights()
    {
    	$weights = $this->find('list', array('conditions' => array('DisciplinesTeacher.weight >' => 0), 'fields' => array('DisciplinesTeacher.id', 'DisciplinesTeacher.discipline_id')));
    	$count = array_count_values($weights);
    	asort($count);
    	return $count;
    }
}
